package handlers

import (
	"github.com/gin-gonic/gin"
	"order-master/models"
	"strconv"
)

func Add(c *gin.Context) {
	goods_name := c.PostForm("goods_name")
	goods_price, _ := strconv.Atoi(c.PostForm("goods_price"))
	goods_no := c.PostForm("goods_no")

	if goods_name == "" || goods_price == 0 || goods_no == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.Goods{
		GoodsName:  goods_name,
		GoodsPrice: goods_price,
		GoodsNo:    goods_no,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var goods []models.Goods
	models.DB.Offset(offset).Limit(size).Find(&goods)

	var total int64
	models.DB.Model(&models.Goods{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  goods,
		"total": total,
	})
	return
}
